# -*- coding: utf-8 -*-
# from __future__ import unicode_literals

from django.shortcuts import render,render_to_response
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate
from django.contrib import auth
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.core.cache import cache
from django.http import HttpResponse,StreamingHttpResponse

from forms import UserForm
from auxiliarytool.md5Handler import getMd5
from auxiliarytool.dirHandler import makeDir
from auxiliarytool.word2txt import Word2Txt
import logging
import chardet
import time
import datetime
import os,tempfile,zipfile
from wsgiref.util import FileWrapper
import xlwt
import json
import shutil
from collections import OrderedDict
from moonAux.zipHandler import ZipUtilities
from demo.config import maxSize,wordDir,customInfoDir,customInfoDirTemp,errorInfoDir,sampleDirOne,sampleDirTwo,sampleTempDir,stopTime

from auxiliarytool.unitHandler import qq,email,address,mobilphone,telphone,url,weichat,otherHandle,companyName

# Create your views here.
logger = logging.getLogger("django")

@csrf_exempt
def login_view(req):
    context = {}
    if req.method == 'POST':

        hour=datetime.datetime.now().hour
        if hour <=stopTime:
            return render(req, 'mercury/login.html', context)

        form = UserForm(req.POST)
        if form.is_valid():
            #获取表单用户密码
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            #获取的表单数据与数据库进行比较
            user = authenticate(username = username,password = password)
            if user:
                #比较成功，跳转index
                auth.login(req,user)
                req.session['username'] = username
                return  redirect('/mercury/index')
            else:
                #比较失败，还在login
                context = {'isLogin': False,'pawd':False}
                return render(req, 'mercury/login.html', context)
    else:
        context = {'isLogin': False,'pswd':True}
    return render(req, 'mercury/login.html', context)

# 退出登录
def logout_view(req):
    #清理cookie里保存username
    auth.logout(req)
    return redirect('/mercury/login')

# 首页面
@login_required
def index(request):
    context = {}
    hour=datetime.datetime.now().hour
    if hour <=stopTime:
        return render(request, 'mercury/login.html', context)
    # real_ip = request.META['REMOTE_ADDR']
    # print "============================"
    # print real_ip
    # print "============================"
    # print "==========================="
    # print request.session['username']
    # print "==========================="
    # =======================================
    userName=request.session['username']
    real_ip = request.META['REMOTE_ADDR']
    userInfo="userName:"+userName+"-"+"IP:"+real_ip
    # logger.warning("qing qiu page......")
    logger.warning(userInfo)
    # print userInfo
    # =======================================

    return render_to_response('mercury/uploadfile.html')
    # return render_to_response('mercury/uploadfileTemp.html')

#上传文件处理
def uploadFileHandler(request):
    '''
    :param request:
    :return:
    构建数据结构：catalog-{'aaasxdgg123':'自定义分割符'}
    '''
    # =======================================
    userName=request.session['username']
    real_ip = request.META['REMOTE_ADDR']
    userInfo="userName:"+userName+"-"+"IP:"+real_ip
    # logger.warning("qing qiu page......")
    logger.warning(userInfo)
    # print userInfo
    # =======================================

    # 先获取自定义分割文件
    if request.method == "POST":    # 请求方法为POST时，进行处理
        catalogFile =request.FILES.get("customfile", None)    # 获取上传的文件，如果没有文件，则默认为None
        contentFile =request.FILES.get("contentfile", None)    # 获取上传的文件，如果没有文件，则默认为None
        if not catalogFile:
            return HttpResponse("请选择目录文件上传！")
        if not contentFile:
            return HttpResponse("请选择内容文件上传！")

        if contentFile.size > 1024*1024*maxSize:
            return HttpResponse("上传的文件大小不能超过100M")
        txtContent=catalogFile.read()

        fileCharInfo=chardet.detect(txtContent)['encoding']
        # print "-----------------"
        # print fileCharInfo
        # print "-----------------"
        if fileCharInfo ==None:
            res=txtContent.decode('gbk').split('\n')
        elif 'Big5' in fileCharInfo or 'KOI8-R' in fileCharInfo:
            res=txtContent.decode('gbk').split('\n')   #目录中每一个标志行,res里面每行内容的编码是unicode
        elif 'TIS' in fileCharInfo:
            res=txtContent.decode('gb2312').split('\n')
        else:
            res=txtContent.decode(fileCharInfo).split('\n')   #目录中每一个标志行,res里面每行内容的编码是unicode
        res1=list(set(res))
        res1.sort(key=res.index)
        res=res1
        catalog=OrderedDict()

        for each in res:
            each=each.strip()
            if len(each)==0:
                continue
            else:
                md5name=getMd5(each)
                catalog[md5name]=each
        #对上传word文件名称进行处理、存储
        wordFullNameList=contentFile.name.split(".")
        wordFileNameMd5=getMd5(wordFullNameList[0]+unicode(time.time()))  #文件名md5
        newWordFullName=wordFileNameMd5+u"."+wordFullNameList[-1]   #文件名md5+后缀
        destination = open(os.path.join(wordDir,newWordFullName),'wb+')    # 打开特定的文件进行二进制的写操作
        for chunk in contentFile.chunks():      # 分块写入文件
            destination.write(chunk)
        destination.close()

    makeDir(customInfoDir,wordFileNameMd5)   #一个word文件对应一个txt文档

    customsegmentInfo(newWordFullName,wordFileNameMd5,catalog) #进行分块并获取信息，此处可能会出现异常

    # 把信息写到cache中
    catalogJson=json.dumps(catalog)
    cache.set(wordFileNameMd5,catalogJson,6000)
    return render_to_response('mercury/transition.html',{'filenameMd5':wordFileNameMd5})

def customsegmentInfo(fileName,parentDirMd5,catalog):
    w2t=Word2Txt()
    # w2t.word2CompanyInfoSegment(wordDir+"\\",fileName,parentDirMd5)
    w2t.word2CustomInfoSegmen(wordDir+"\\",fileName,parentDirMd5,catalog)

# 处理公司名称信息提取流程
def companyNameHandler(request):
    filenameMd5=request.GET.get("filenameMd5")
    tmp=customBuildNameInfoResult(filenameMd5)
    return render_to_response('mercury/companynameresult.html',{'filenameMd5':filenameMd5,'companyInfo':tmp})
def customBuildNameInfoResult(wordMd5):
    wordDir=customInfoDir
    targetDir=wordDir+"\\"+wordMd5
    manyCompanyDir=os.listdir(targetDir)

    catalogJson=cache.get(wordMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)

    result=[]
    for eachDir in manyCompanyDir:
        eachCompanyDir=targetDir+"\\"+eachDir
        fileList=os.listdir(eachCompanyDir)      #表示一个数据块中有多少个联系方式单元
        try:
            companyNameL=companyName(eachCompanyDir,fileList,eachDir)
            res={}
            res['id']=catalog[eachDir]
            res['companyName']=showOne(companyNameL)
            result.append(res)
        except:
            continue
    return result

def customBuildNameDetailInfoResult(wordMd5):
    wordDir=customInfoDir
    targetDir=wordDir+"\\"+wordMd5
    manyCompanyDir=os.listdir(targetDir)

    catalogJson=cache.get(wordMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)
    result=[]
    for eachDir in manyCompanyDir:
        eachCompanyDir=targetDir+"\\"+eachDir
        fileList=os.listdir(eachCompanyDir)      #表示一个数据块中有多少个联系方式单元
        try:
            companyNameL=companyName(eachCompanyDir,fileList,eachDir)
            res={}
            res['id']=catalog[eachDir]
            res['companyName']=set(companyNameL)
            result.append(res)
        except:
            continue
    return result

def downloadNameInfo(request):
    # =======================================
    userName=request.session['username']
    real_ip = request.META['REMOTE_ADDR']
    userInfo="userName:"+userName+"-"+"IP:"+real_ip
    # logger.warning("qing qiu page......")
    logger.warning(userInfo)
    # print userInfo
    # =======================================

    wordMd5=request.GET.get('filenameMd5')

    tmps=customBuildNameDetailInfoResult(wordMd5)
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('企业名称信息')
    ws.write(0, 0, 'Id')
    ws.write(0, 1, '企业名称')
    excel_row = 1

    for tmp in tmps:
        try:
            ws.write(excel_row, 0, tmp['id'])
            ws.write(excel_row, 1, ";".join(tmp['companyName']))
            excel_row = excel_row + 1
        except:
            continue
    #
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=公司名称.xls'
    wb.save(response)
    return response
def downloadNameFenpianFile(request):
    parentMd5=request.GET.get('filenameMd5')
    targetDir=customInfoDir+"\\"+parentMd5
    manyCompanyDir=os.listdir(targetDir)  #多个分块文件信息

    catalogJson=cache.get(parentMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)
    temp = tempfile.TemporaryFile()
    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    #
    for each in manyCompanyDir:
        full_path=customInfoDir+"\\"+parentMd5+"\\"+each+"\\"+each+"companyName.txt"
        isErrorFlie=os.path.exists(full_path)
        if isErrorFlie:
            archive.write(full_path,catalog[each]+u'.txt')
        else:
            continue
    archive.close()
    data=temp.tell()
    temp.seek(0)

    wrapper = FileWrapper(temp)
    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=companyName.zip'
    response['Content-Length'] = data
    return response

# 处理联系方式信息提取流程
def contactHandler(request):
    filenameMd5=request.GET.get("filenameMd5")
    tmp=customBuildInfoResult(filenameMd5)
    full_path = os.path.join(errorInfoDir, filenameMd5+'.txt')
    errorFlie=os.path.exists(full_path)
    return render_to_response('mercury/contactresult.html',{'filenameMd5':filenameMd5,'contactInfo':tmp,'error':errorFlie})
def customBuildInfoResult(wordFileMd5):
    wordDir=customInfoDir
    targetDir=wordDir+"\\"+wordFileMd5
    manyCompanyDir=os.listdir(targetDir)

    # 获取catalog的内容信息
    catalogJson=cache.get(wordFileMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)

    result=[]
    for eachDir in manyCompanyDir:
        eachCompanyDir=targetDir+"\\"+eachDir
        fileList=os.listdir(eachCompanyDir)      #表示一个数据块中有多少个联系方式单元
        # if len(fileList)<5:        #每一个单元模块都会有fullInfo.txt，联系单元种类阈值设置为3
        #     continue
        qqL=qq(eachCompanyDir,fileList,eachDir)
        emailL=email(eachCompanyDir,fileList,eachDir)
        # 地址仅仅识别一个
        addressL=address(eachCompanyDir,fileList,eachDir)
        mobilphoneL=mobilphone(eachCompanyDir,fileList,eachDir)
        telphoneL=[]
        Temp=telphone(eachCompanyDir,fileList,eachDir)
        telphoneL+=Temp[0]
        mobilphoneL+=Temp[1]


        urlL=url(eachCompanyDir,fileList,eachDir)
        weichatL=weichat(eachCompanyDir,fileList,eachDir)
        # --------------------------------------------------------
        otherRes=otherHandle(eachCompanyDir,fileList,eachDir)

        emailL+=otherRes['email']
        addressL+=otherRes['address']
        urlL+=otherRes['url']
        mobilphoneL+=otherRes['mobilphone']
        telphoneL+=otherRes['telphone']
        res={}
        res['Id']=catalog[eachDir]
        res['qq']=showOne(qqL)
        res['email']=showOne(emailL)
        res['address']=showOne(addressL)
        res['mobilphone']=showOne(mobilphoneL)
        res['telphone']=showOne(telphoneFilter(telphoneL))
        res['url']=showOne(urlL)
        res['weichat']=showOne(weichatL)
        result.append(res)
    return result
def customBuildDetailInfo(wordFileMd5):
    wordDir=customInfoDir
    targetDir=wordDir+"\\"+wordFileMd5
    manyCompanyDir=os.listdir(targetDir)

    # 获取catalog的内容信息
    catalogJson=cache.get(wordFileMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)

    result=[]
    for eachDir in manyCompanyDir:
        eachCompanyDir=targetDir+"\\"+eachDir
        fileList=os.listdir(eachCompanyDir)      #表示一个数据块中有多少个联系方式单元
        # if len(fileList)<5:        #每一个单元模块都会有fullInfo.txt，联系单元种类阈值设置为3
        #     continue
        qqL=qq(eachCompanyDir,fileList,eachDir)
        emailL=email(eachCompanyDir,fileList,eachDir)
        # 地址仅仅识别一个
        addressL=address(eachCompanyDir,fileList,eachDir)
        mobilphoneL=mobilphone(eachCompanyDir,fileList,eachDir)
        telphoneL=[]
        Temp=telphone(eachCompanyDir,fileList,eachDir)
        telphoneL+=Temp[0]
        mobilphoneL+=Temp[1]


        urlL=url(eachCompanyDir,fileList,eachDir)
        weichatL=weichat(eachCompanyDir,fileList,eachDir)
        # --------------------------------------------------------
        otherRes=otherHandle(eachCompanyDir,fileList,eachDir)

        emailL+=otherRes['email']
        addressL+=otherRes['address']
        urlL+=otherRes['url']
        mobilphoneL+=otherRes['mobilphone']
        telphoneL+=otherRes['telphone']

        mobilphoneL=deleteMobilPhoneChar(mobilphoneL)

        res={}
        res['Id']=catalog[eachDir]
        res['qq']=set(qqL)
        res['email']=set(emailL)
        res['address']=set(addressL)
        res['mobilphone']=set(mobilphoneL)
        res['telphone']=set(telphoneFilter(telphoneL))
        res['url']=set(urlL)
        res['weichat']=set(weichatL)
        result.append(res)
    return result

def downloadDetailInfo(request):

    # =======================================
    userName=request.session['username']
    real_ip = request.META['REMOTE_ADDR']
    userInfo="userName:"+userName+"-"+"IP:"+real_ip
    # logger.warning("qing qiu page......")
    logger.warning(userInfo)
    # print userInfo
    # =======================================
    wordMd5=request.GET.get('filenameMd5')

    tmps=customBuildDetailInfo(wordMd5)
    wb = xlwt.Workbook(encoding='utf-8')
    ws = wb.add_sheet('联系信息')
    ws.write(0, 0, '自定义分隔符')
    ws.write(0, 1, 'QQ')
    ws.write(0, 2, '邮箱')
    ws.write(0, 3, '地址')
    ws.write(0, 4, '手机')
    ws.write(0, 5, '电话')
    ws.write(0, 6, '网址')
    ws.write(0, 7, '微信')
    #
    excel_row = 1

    for tmp in tmps:
        try:
            ws.write(excel_row, 0, tmp['Id'])
            ws.write(excel_row, 1, ";".join(tmp['qq']))
            ws.write(excel_row, 2, ";".join(tmp['email']))
            ws.write(excel_row, 3, ";".join(tmp['address']))
            ws.write(excel_row, 4, ";".join(tmp['mobilphone']))
            ws.write(excel_row, 5, ";".join(tmp['telphone']))
            ws.write(excel_row, 6, ";".join(tmp['url']))
            ws.write(excel_row, 7, ";".join(tmp['weichat']))
            excel_row = excel_row + 1
        except:
            continue
    #
    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=result.xls'
    wb.save(response)
    return response

def downloadCustomFenkuaiFile(request):
    parentMd5=request.GET.get('filenameMd5')
    targetDir=customInfoDir+"\\"+parentMd5
    manyCompanyDir=os.listdir(targetDir)  #多个分块文件信息

    catalogJson=cache.get(parentMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)
    temp = tempfile.TemporaryFile()
    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    #
    for each in manyCompanyDir:
        archive.write(customInfoDir+"\\"+parentMd5+"\\"+each+"\\"+"fullInfo.txt",catalog[each]+u'.txt')
    archive.close()
    data=temp.tell()
    temp.seek(0)

    wrapper = FileWrapper(temp)
    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=test.zip'
    response['Content-Length'] = data
    return response

def downloadMiddleStep1_2(request):
    parentMd5=request.GET.get('filenameMd5')
    targetDir=customInfoDir+"\\"+parentMd5
    manyCompanyDir=os.listdir(targetDir)  #多个分块文件信息

    catalogJson=cache.get(parentMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)
    temp = tempfile.TemporaryFile()
    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    #
    for each in manyCompanyDir:
        #添加异常处理，如果不存在对应文件时需要进行相应操作
        full_path=customInfoDir+"\\"+parentMd5+"\\"+each+"\\"+"step1-2.txt"
        isErrorFlie=os.path.exists(full_path)
        if isErrorFlie:
            archive.write(full_path,catalog[each]+u'.txt')
        else:
            continue
    archive.close()
    data=temp.tell()
    temp.seek(0)

    wrapper = FileWrapper(temp)
    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=step1-2.zip'
    response['Content-Length'] = data
    return response

def downloadMiddleStep1_3(request):
    parentMd5=request.GET.get('filenameMd5')
    targetDir=customInfoDir+"\\"+parentMd5
    manyCompanyDir=os.listdir(targetDir)  #多个分块文件信息

    catalogJson=cache.get(parentMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)
    temp = tempfile.TemporaryFile()
    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)

    for each in manyCompanyDir:
        full_path=customInfoDir+"\\"+parentMd5+"\\"+each+"\\"+"step1-3.txt"
        isErrorFlie=os.path.exists(full_path)
        if isErrorFlie:
            archive.write(full_path,catalog[each]+u'.txt')
        else:
            continue
    archive.close()
    data=temp.tell()
    temp.seek(0)

    wrapper = FileWrapper(temp)
    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=step1-3.zip'
    response['Content-Length'] = data
    return response

def downloadMiddleStep1_4(request):
    parentMd5=request.GET.get('filenameMd5')
    targetDir=customInfoDir+"\\"+parentMd5
    manyCompanyDir=os.listdir(targetDir)  #多个分块文件信息

    catalogJson=cache.get(parentMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)
    temp = tempfile.TemporaryFile()
    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    #
    for each in manyCompanyDir:
        full_path=customInfoDir+"\\"+parentMd5+"\\"+each+"\\"+"step1-4.txt"
        isErrorFlie=os.path.exists(full_path)
        if isErrorFlie:
            archive.write(full_path,catalog[each]+u'.txt')
        else:
            continue
    archive.close()
    data=temp.tell()
    temp.seek(0)

    wrapper = FileWrapper(temp)
    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=step1-4.zip'
    response['Content-Length'] = data
    return response

def downloadMiddleStep1_5(request):
    parentMd5=request.GET.get('filenameMd5')
    targetDir=customInfoDir+"\\"+parentMd5
    manyCompanyDir=os.listdir(targetDir)  #多个分块文件信息

    catalogJson=cache.get(parentMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)
    temp = tempfile.TemporaryFile()
    archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED)
    #
    for each in manyCompanyDir:
        full_path=customInfoDir+"\\"+parentMd5+"\\"+each+"\\"+"step1-5.txt"
        isErrorFlie=os.path.exists(full_path)
        if isErrorFlie:
            archive.write(full_path,catalog[each]+u'.txt')
        else:
            continue
    archive.close()
    data=temp.tell()
    temp.seek(0)

    wrapper = FileWrapper(temp)
    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=step1-5.zip'
    response['Content-Length'] = data
    return response

def downloadCustomFenPianFile(request):
    parentMd5=request.GET.get('filenameMd5')

    catalogJson=cache.get(parentMd5)
    if catalogJson!=None:
        catalog=json.loads(catalogJson)
    # return HttpResponse('ok')
    catalog=json.loads(catalogJson)
    sourceDir=customInfoDir+"\\"+parentMd5
    #进行复制操作
    targetDir=customInfoDirTemp+"\\"+parentMd5
    shutil.copytree(sourceDir,targetDir,ignore=shutil.ignore_patterns('fullInfo.txt','*companyName.txt','*step*.txt'))
    # 对文件夹进行重命名
    # [0]表示名字,[1]表示md5
    for k,v in catalog.items():
        os.rename(os.path.join(targetDir,k),os.path.join(targetDir,v))

    utilities = ZipUtilities()
    utilities.toZip(targetDir,u"自定义格式分片文件")
    response = StreamingHttpResponse(utilities.zip_file, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=temp.zip'
    return response

def downloadErrorFile(request):
    parentMd5=request.GET.get('filenameMd5')
    response = HttpResponse()
    response['Content-Disposition'] = 'attachment;filename=错误记录.txt'
    full_path = os.path.join(errorInfoDir, parentMd5+'.txt')
    if os.path.exists(full_path):
        response['Content-Length'] = os.path.getsize(full_path)    #  可不加
        content = open(full_path, 'rb').read()
        response.write(content)
        return response
    else:
        return HttpResponse(u'文件未找到,没有错误')

def showOne(target):
    if len(target)!=0:
        return target[0]
    else:
        return ""

def returnHandler(request):
    # return render_to_response('moon/uploadfile.html')
    return redirect('/mercury/index')

def telphoneFilter(targetList):
    # if len(targetList)==1:
    #     return targetList
    # print "-----------22-------------"
    # print targetList
    # print "-----------22-------------"
    num=[]
    numList=[]
    fullNum=[]
    fullNumList=[]
    for each in targetList:
        if '-' in each and each.find('-')<=4 and each.find('-')!=-1:
            fullNum.append(each)
        else:
            num.append(each)

    for each in num:
        if each.startswith('1') or each.startswith('0'):
            continue
        else:
            numList.append(each)

    for each in fullNum:
        res=each.split('-')
        if len(res)==2 and len(res[0])<5:
            if res[-1].startswith('1') or res[-1].startswith('0') or res[0].startswith('1'):
                continue
            else:
                fullNumList.append(each)
        else:
            fullNumList.append(each)

    if len(fullNumList)==0:
        return numList
    if len(numList)==0:
        return fullNumList

    quhao=''
    for each in fullNumList:
        target=each.split('-')[0]
        if len(target)<5:
            quhao=target
            break

    # quhao=fullNumList[0].split('-')[0]

    for onenum in numList:
        if onenum.startswith('400') or onenum.startswith('800'):
            fullNumList.append(onenum)
        else:
            if quhao !='':
                temp=quhao+"-"+onenum
                fullNumList.append(temp)
            else:
                fullNumList.append(onenum)

    return fullNumList


def deleteMobilPhoneChar(targetList):
    temp=[]
    for each in targetList:
        each=each.replace('-','')
        temp.append(each)
    return temp


def showbutton(request):
    return render_to_response('mercury/showbutton.html')


def downloadsampleone(request):
    sourceDir=sampleDirOne
    #进行复制操作
    uuid=getMd5(unicode(time.time()))
    targetDir=sampleTempDir+"\\"+uuid
    shutil.copytree(sourceDir,targetDir)
    # 对文件夹进行重命名
    # [0]表示名字,[1]表示md5
    # for k,v in catalog.items():
    #     os.rename(os.path.join(targetDir,k),os.path.join(targetDir,v))

    utilities = ZipUtilities()
    utilities.toZip(targetDir,u"样例一")
    response = StreamingHttpResponse(utilities.zip_file, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=sample1.zip'
    return response

def downloadsampletwo(request):
    sourceDir=sampleDirTwo
    #进行复制操作
    uuid=getMd5(unicode(time.time()))
    targetDir=sampleTempDir+"\\"+uuid
    shutil.copytree(sourceDir,targetDir)

    utilities = ZipUtilities()
    utilities.toZip(targetDir,u"样例二")
    response = StreamingHttpResponse(utilities.zip_file, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=sample2.zip'
    return response